package org.uim.cricket.analyzer.parsers.inning.impl;

import org.uim.cricket.analyzer.parsers.inning.InningExtrasParsable;
import org.uim.cricket.entities.inning.InningExtras;
import org.uim.cricket.util.HTMLStringUtils;
import org.uim.cricket.util.MyStringUtils;

public class DefaultInningExtrasParser implements InningExtrasParsable {

	@Override
	public InningExtras parseExtras(String source) {
		if (source == null) return null;
		String[] datarows = MyStringUtils.splitInBetween(source, "<td", "</td>");

		if (datarows.length < 3) return null;
		
		String tmp = HTMLStringUtils.cleanHTMLTags("<" + datarows[2]);
		return getExtras(tmp);
	}

	private InningExtras getExtras(String src) {
		src = MyStringUtils.replaceAll(src, "", "\\(", "\\)");
		InningExtras extras = new InningExtras();
		String[] extypes = src.split("[,]");
		
		for (int i=0;i<extypes.length;i++) {
			extypes[i] = extypes[i].trim();
			String[] attrb = extypes[i].split("[ ]+");
			
			if (attrb.length < 2) continue;
			
			if ("lb".equals(attrb[0])) {
				extras.setLegBies(Integer.parseInt(attrb[1]));
			} else if ("b".equals(attrb[0])) {
				extras.setBies(Integer.parseInt(attrb[1]));
			} else if ("nb".equals(attrb[0])) {
				extras.setNoBalls(Integer.parseInt(attrb[1]));
			} else if ("w".equals(attrb[0])) {
				extras.setWides(Integer.parseInt(attrb[1]));
			} else if ("pen".equals(attrb[0])) {
				extras.setPanelties(Integer.parseInt(attrb[1]));
			}
			
		}
		
		return extras;
	}
	
	
}
